package com.streamer.app.fragment

import android.graphics.drawable.BitmapDrawable
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.streamer.app.R
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.streamer.app.BaseActivity
import com.streamer.app.bean.LiveBean
import com.streamer.app.databinding.FragmentPptWhiteboardBinding
import com.streamer.app.widget.WhiteboardDrawingView

class PPTWhiteboardFragment : BaseFragment<FragmentPptWhiteboardBinding>() {

    private var mliveData: LiveBean? = null


    // 当前选中的工具
    private var currentSelectedTool: ImageView? = null

    // 课件分页数据
    private var coursewarePages: MutableList<Any> = mutableListOf()
    private var currentPageIndex: Int = 0


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mliveData = (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable(ARG_LIVE_DATA, LiveBean::class.java)
        } else {
            @Suppress("DEPRECATION") arguments?.getSerializable(ARG_LIVE_DATA)
        }) as LiveBean?

    }


    override fun initView() {
        initViews()
    }

    private fun initViews() {
        val drawingView = _binding.drawingView
        // 设置默认选中移动工具
        setSelectedTool(_binding.btnMove)

        _binding.btnMove.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.PAN)
            setSelectedTool(_binding.btnMove)
        }
        _binding.btnPen.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.DRAW)
            drawingView.setStrokeWidth(6f) // 设置普通画笔粗细
            showBrushPicker(this@PPTWhiteboardFragment, drawingView, false)
            setSelectedTool(_binding.btnPen)
        }
        _binding.btnEraser?.setOnClickListener {
            drawingView.setMode(WhiteboardDrawingView.ToolMode.DRAW)
            // 调用基类方法并传入 drawingView
            showBrushPicker(this@PPTWhiteboardFragment, drawingView, true)
            setSelectedTool(_binding.btnEraser)
        }
        _binding.btnLine?.setOnClickListener {
            drawingView?.setMode(WhiteboardDrawingView.ToolMode.LINE)
            setSelectedTool(_binding.btnLine)
        }
        _binding.btnText?.setOnClickListener {
            drawingView?.setMode(WhiteboardDrawingView.ToolMode.TEXT)
            setSelectedTool(_binding.btnText)
        }
        _binding.btnShape?.setOnClickListener {
            drawingView?.setMode(WhiteboardDrawingView.ToolMode.ERASE_WHITE_CIRCLE)
            drawingView?.setWhiteEraserRadius(18f)
            setSelectedTool(_binding.btnShape)
        }
        _binding.btnFill?.setOnClickListener {
            drawingView?.clearAll()
            // 填充工具不需要选中状态，因为它是操作而不是模式
        }
        // 监听课件列表，缓存到本地，供弹窗选择
        viewMode.CoursewareListLV.observe(requireActivity()) { coursewareData ->
            coursewareData?.let {
                coursewareList.clear()
                coursewareList.addAll(it)
            }
        }
        // 监听课件选择结果，驱动分页与显示
        viewMode.CoursewareInfoLV.observe(requireActivity()) { list ->
            when {
                list.isNullOrEmpty() -> {
                    _binding.bottomControls.visibility = View.GONE
                    coursewarePages.clear()
                    currentPageIndex = 0
                    _binding.drawingView.background = null
                    _binding.drawingView.clearAll()
                    updatePageInfo(1, 1)
                }

                list[0].conversionContent.isEmpty() -> {
                    _binding.bottomControls.visibility = View.GONE
                    coursewarePages.clear()
                    currentPageIndex = 0
                    _binding.drawingView.background = null
                    _binding.drawingView.clearAll()
                    updatePageInfo(1, 1)
                }

                else -> {
                    val contents = list[0].conversionContent
                    _binding.bottomControls.visibility = View.VISIBLE
                    coursewarePages.clear()
                    coursewarePages.addAll(contents)
                    currentPageIndex = 0
                    setupPagingControls()
                    showPage(0)
                }
            }
        }
        viewMode.CoursewareListLV.observe(requireActivity()) { coursewareData ->
            coursewareData?.let {
                coursewareList.clear()
                coursewareList.addAll(it)
                Log.d("WhiteboardFragment", "课件列表数据更新，共 ${it.size} 个文件")
            }
        }
        drawingView?.setOnRequestText { x, y ->
            val input = EditText(requireContext())
            input.hint = "输入文字"
            MaterialAlertDialogBuilder(requireContext()).setTitle("添加文字").setView(input)
                .setPositiveButton("确定") { d, _ ->
                    val t = input.text?.toString()?.trim()
                    if (!t.isNullOrEmpty()) drawingView?.addTextAt(t, x, y)
                    d.dismiss()
                }.setNegativeButton("取消") { d, _ -> d.dismiss() }.show()
        }
    }

    private fun setupPagingControls() {
        _binding.btnPrevPage.setOnClickListener {
            if (currentPageIndex > 0) {
                showPage(currentPageIndex - 1)
            }
        }
        _binding.btnNextPage.setOnClickListener {
            val total = coursewarePages.size
            if (currentPageIndex < total - 1) {
                showPage(currentPageIndex + 1)
            }
        }
        updatePageInfo(
            (currentPageIndex + 1).coerceAtLeast(1), coursewarePages.size.coerceAtLeast(1)
        )
    }

    private fun updatePageInfo(current: Int, total: Int) {
        _binding.tvPageInfo.text = "$current/$total"
    }

    private fun showPage(index: Int) {
        currentPageIndex = index
        val total = coursewarePages.size.coerceAtLeast(1)
        if (coursewarePages.isEmpty()) {
            _binding.drawingView.background = null
            _binding.drawingView.clearAll()
            updatePageInfo(1, 1)
            return
        }
        val pageIdx = index.coerceIn(0, coursewarePages.size - 1)
        val url = coursewarePages[pageIdx].toString()
        _binding.drawingView.clearAll()
        Glide.with(requireContext()).asBitmap().load(url)
            .into(object : CustomTarget<android.graphics.Bitmap>() {
                override fun onResourceReady(
                    resource: android.graphics.Bitmap,
                    transition: Transition<in android.graphics.Bitmap>?
                ) {
                    _binding.drawingView.background = BitmapDrawable(resources, resource)
                }

                override fun onLoadCleared(placeholder: android.graphics.drawable.Drawable?) {}
            })
        updatePageInfo(pageIdx + 1, total)
    }


    /**
     * 设置选中的工具按钮
     */
    private fun setSelectedTool(selectedTool: ImageView?) {
        // 清除之前选中工具的背景
        currentSelectedTool?.background = null

        // 设置新选中工具的背景
        selectedTool?.background = requireContext().getDrawable(R.drawable.tool_button_selected)

        // 更新当前选中的工具
        currentSelectedTool = selectedTool
    }

    // 已抽取到 BaseFragment：showBrushPicker / ColorVH / dp

    /**
     * 从 LiveVideoFragment
     */
    fun startRecordingFromVideoFragment(pushLive3PUrl: String) {
        Log.d("PPTWhiteboardFragment", "startRecordingFromVideoFragment called with URL: $pushLive3PUrl")
        
        // 确保 drawingView 已经布局完成
        if (_binding.drawingView.width <= 0 || _binding.drawingView.height <= 0) {
            _binding.drawingView.post {
                startRecordingFromVideoFragment(pushLive3PUrl)
            }
            return
        }
        
        // 直接录白板画布，避免容器里还有其他视图
        // 开始前强制切到外部源，避免摄像头画面混入
        try {
            val activity = requireActivity() as? com.streamer.app.BaseActivity
            // BaseActivity.startRecord 内部已根据协议选择推流实现
            activity?.startRecord(_binding.drawingView, pushLive3PUrl.replace("artc://","rtmp://"))
        } catch (_: Exception) {
        }
        
    }

    companion object {
        private const val ARG_LIVE_DATA = "liveData"
        fun newInstance(mliveData: LiveBean?): PPTWhiteboardFragment {
            val f = PPTWhiteboardFragment()
            val b = Bundle()
            b.putSerializable(ARG_LIVE_DATA, mliveData)
            f.arguments = b
            return f
        }
    }
}